//
//  TDCarDetailC.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/5.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TDCarDetailC.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "BONoticeBar.h"
#import "TDCarDetailScrollCell.h"
#import "TDCarDetailDescCell.h"
#import "TDCarDetailIsCanOrderCell.h"
#import "TDCarDetailStoreAddressCell.h"

#import "DWQRatingView.h"
#import "TDDetailCarModel.h"

#import "TDCarDetailDescC.h"
#import "TDCalendaViewShowC.h"
#import "YXDateHelpObject.h"
#import "UILabel+height.h"

#import "TDYuDingDetailC.h"
#import "NetWorkRequest.h"
#import <UIImageView+WebCache.h>
@interface TDCarDetailC ()<UITableViewDelegate,UITableViewDataSource,TDCarDetailDescCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;


@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIView *nav_lineView;
@property (weak, nonatomic) IBOutlet UILabel *nav_title;

@property (weak, nonatomic) IBOutlet UIImageView *nav_leftImv;
@property (weak, nonatomic) IBOutlet UIImageView *nav_rightImg;


@property (weak, nonatomic) IBOutlet UIView *view_container_star;//五星的容器视图---
@property (nonatomic,strong)TDCarSourceDetailModel *detailCarModel;

@property (weak, nonatomic) IBOutlet UILabel *lbe_price;

@property (weak, nonatomic) IBOutlet UILabel *lbe_star;

@property (nonatomic,strong)DWQRatingView *starView;

@property (weak, nonatomic) IBOutlet UIButton *btn_yuding;

@end

@implementation TDCarDetailC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //    CLLocationCoordinate2D storeLocation = CLLocationCoordinate2DMake(31.1935500000,121.4536100000);
    //    [_mapView setCenterCoordinate:storeLocation animated:                                                                                                                    YES];
}

- (void)setupUI {
    //设置导航条
    [self setupNavItem:YES];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCarDetailScrollCell" bundle:nil] forCellReuseIdentifier:@"TDCarDetailScrollCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCarDetailDescCell" bundle:nil] forCellReuseIdentifier:@"TDCarDetailDescCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCarDetailDesc2Cell" bundle:nil] forCellReuseIdentifier:@"TDCarDetailDesc2CellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCarDetailIsCanOrderCell" bundle:nil] forCellReuseIdentifier:@"TDCarDetailIsCanOrderCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCarDetailStoreAddressCell" bundle:nil] forCellReuseIdentifier:@"TDCarDetailStoreAddressCellId"];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
    [self setupBottomView];
}

- (void)setupBottomView {
    [self.view_container_star addSubview:self.starView];
    _btn_yuding.layer.cornerRadius = 5;
    _btn_yuding.layer.masksToBounds = YES;
    [self.starView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.top.offset(0);
    }];
//    starView.needIntValue=NO;   //是否整数显示，默认整数显示
    self.starView.canTouch=NO;//是否可以点击，默认为NO
    //start2.scoreNum=@4;//星星显示个数
    self.starView.normalColorChain([UIColor lightGrayColor]);
    self.starView.highlightColorChian([UIColor redColor]);
    self.starView.scroreBlock=^(NSNumber *number){
        NSLog(@"返回的分数");
    };
}

- (DWQRatingView *)starView {
    if (!_starView) {
        _starView = [[DWQRatingView alloc] init];
    }
    return _starView;
}

- (void)setupNavItem:(BOOL)isDefault {
    if (isDefault) {
        self.nav_leftImv.image = [UIImage imageNamed:@"返回"];
        self.nav_rightImg.image = [UIImage imageNamed:@"分享"];
        self.navView.backgroundColor = [UIColor clearColor];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
        self.nav_lineView.hidden = YES;
        self.nav_title.text = @"";
    }else {
        self.nav_leftImv.image = [UIImage imageNamed:@"返回选中"];
        self.nav_rightImg.image = [UIImage imageNamed:@"分享选中"];
        self.navView.backgroundColor = [UIColor whiteColor];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
        self.nav_title.text = [NSString stringWithFormat:@"%@ %@",_detailCarModel.brandnm,_detailCarModel.seriesnm];
        self.nav_lineView.hidden = NO;
    }
}

// MARK: - 返回和分享按钮点击事件--------
- (IBAction)navBtnClick:(UIButton *)sender {
    if (sender.tag == 10) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        //分享按钮点击事件
        [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone),@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
        //    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
            // 根据获取的platformType确定所选平台进行下一步操作
            [self shareWebPageToPlatformType:platformType];
        }];
    }
}

// MARK: - 预定按钮点击事件-----
- (IBAction)yuDingBtnClick:(UIButton *)sender {
    
    if ([HelpObject isBlankString:self.selDateModel.yearStr] || [HelpObject isBlankString:self.selDateModel.yearEndStr]) {
        self.noticeText = @"请先选择试驾时间段";
        return;
    }
    
    if ([HelpObject isBlankString:self.selDateModel.startHourStr] || [HelpObject isBlankString:self.selDateModel.endHourStr]) {
        self.selDateModel.startHourStr = self.detailCarModel.servicetimefrom;
        self.selDateModel.endHourStr = self.detailCarModel.servicetimeto;
    }
    
    TDYuDingDetailC *yuDingDetailC = [[TDYuDingDetailC alloc] init];
    yuDingDetailC.detailCarModel = self.detailCarModel;
    
    
    // MARK: - 吧选中的时间也传递过去-------------------------
    yuDingDetailC.selDateModel = self.selDateModel;
    [self.navigationController pushViewController:yuDingDetailC animated:YES];
}



#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getIdentifier:indexPath] forIndexPath:indexPath];
    [self setupCell:cell indexPath:indexPath];
    return cell;
}

- (NSString *)getIdentifier:(NSIndexPath *)indexPath {
    NSString *iden = @"TDCarDetailScrollCellId";
    if (indexPath.row == 0) {
        iden = @"TDCarDetailScrollCellId";
    }else if(indexPath.row == 1) {
        if ([_detailCarModel.isShowAllDetailDesc isEqualToString:@"1"]) {
            iden = @"TDCarDetailDescCellId";
        }else {
            iden = @"TDCarDetailDesc2CellId";
        }
    }else if (indexPath.row == 2) {
        iden = @"TDCarDetailIsCanOrderCellId";
    }else if (indexPath.row == 3) {
        iden = @"TDCarDetailStoreAddressCellId";
    }
    return iden;
}

- (void)setupCell:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (indexPath.row == 0) {
        TDCarDetailScrollCell *carScrollCell = (TDCarDetailScrollCell *)cell;
        carScrollCell.detailCarModel = self.detailCarModel;
    }else if (indexPath.row == 1) {
        TDCarDetailDescCell *carDescCell = (TDCarDetailDescCell *)cell;
        carDescCell.detailCarModel = self.detailCarModel;
        carDescCell.delegate = self;
    }else if (indexPath.row == 2) {
        TDCarDetailIsCanOrderCell *isCanOrderCell = (TDCarDetailIsCanOrderCell *)cell;
        isCanOrderCell.detailCarModel = self.detailCarModel;

    }else if (indexPath.row == 3) {
        TDCarDetailStoreAddressCell *carDetailStoreAddressCell = (TDCarDetailStoreAddressCell *)cell;
        carDetailStoreAddressCell.detailCarModel = self.detailCarModel;
        NSString *urlStr = [NSString stringWithFormat:@"http://api.map.baidu.com/staticimage?width=335&height=220&center=%@,%@&zoom=13&markers=%@,%@&markerStyles=0xBF0021",_detailCarModel.longitude,_detailCarModel.latitude,_detailCarModel.longitude,_detailCarModel.latitude];
        [carDetailStoreAddressCell.imv_storeAddress sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"car"]];
        
    }
}


- (void)detailDescCellShowDescBtnClick:(NSInteger)tag {
    TDCarDetailDescC *carDetailDescC = [[TDCarDetailDescC alloc] init];
    carDetailDescC.contentText = _detailCarModel.profile;
    [self.navigationController pushViewController:carDetailDescC animated:YES];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // MARK: - 日历选中事件------------------
    if (indexPath.row == 2) {
        TDCalendaViewShowC *calendaViewShowC = [[TDCalendaViewShowC alloc] init];
        calendaViewShowC.allSchedulelist = self.detailCarModel.schedulelist;
        calendaViewShowC.detailCarModel = self.detailCarModel;
        __weak typeof(self) weakSelf = self;
        calendaViewShowC.calendaViewShowCBlock = ^(NSString *startStr, NSString *endStr, NSDate *startDate, NSDate *endDate) {
            NSInteger tmpDuration = [YXDateHelpObject numberOfDaysWithFromDate:startDate toDate:endDate];
            weakSelf.selDateModel.timeDurationStr = [NSString stringWithFormat:@"%ld",tmpDuration + 1];
            weakSelf.selDateModel.startHourStr = [startStr componentsSeparatedByString:@" "].lastObject;
            weakSelf.selDateModel.endHourStr = [endStr componentsSeparatedByString:@" "].lastObject;
            weakSelf.selDateModel.yearStr = [[YXDateHelpObject manager] getStrFromDateFormat:@"yyyy/MM/dd" Date:startDate];
            weakSelf.selDateModel.yearEndStr = [[YXDateHelpObject manager] getStrFromDateFormat:@"yyyy/MM/dd" Date:endDate];
        };
        
        [self.navigationController pushViewController:calendaViewShowC animated:YES];
    }
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offY = self.tableView.contentOffset.y;
    NSLog(@"%.2f",offY);
    if (self.tableView.contentOffset.y > 220) {
        [self setupNavItem:NO];
    } else {
        [self setupNavItem:YES];
    }
}


// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
    [self loadNetData];
}
// MARK: - 本地数据
- (void)loadLocalData {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeSelDate:) name:@"kRemoveTDSelDate" object:nil];
}

- (void)removeSelDate:(NSNotification *)noti {
    [self loadNetData];
    self.selDateModel = [[TDDriveCarDatePickerSelModel alloc] init];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// MARK: - 获取网络数据-----
- (void)loadNetData {
    // MARK: - 获取车源列表--------------
    if (!_locationModel) {
        self.noticeText = @"定位失败,请稍后重试";
        return;
    }
    if ([HelpObject isBlankString:[AppSetting shareAppSetting].topcompanyid]) {
        self.noticeText = @"顶级公司id为空";
        return;
    }
    NSString *carid = [HelpObject changeNull:_carSourceListModel.carid];
    NSString *topcompanyid = [AppSetting shareAppSetting].topcompanyid;
    NSDictionary *parDic = @{
                             @"topcompanyid":topcompanyid,
                             @"longitude":_locationModel.longitude,
                             @"latitude":_locationModel.latitude,
                             @"carid":carid
                             };
    __weak typeof(self) weakSelf = self;
    [self progressHUDShowWithText:nil];
    [NetWorkRequest postNetRequestData:CarDetailTD parmeters:parDic response:^(NSDictionary *response) {
        weakSelf.lbe_price.text = [NSString stringWithFormat:@"¥ %@每天",self.carSourceListModel.price];
        weakSelf.starView.scoreNum= @(self.carSourceListModel.stars.doubleValue);
        weakSelf.lbe_star.text = self.carSourceListModel.stars;
        if (response) {
            [weakSelf progressHUDHideImmediately];
            NSArray *tmpArray = response[@"data"][@"carinfo"];
            weakSelf.detailCarModel = [TDCarSourceDetailModel yy_modelWithJSON:tmpArray.firstObject];
            
            weakSelf.detailCarModel.titleDesc = weakSelf.detailCarModel.profile;
            CGFloat contentWidth = [UILabel calllHeightWithContent:weakSelf.detailCarModel.titleDesc andLineNumber:0 andFont:[UIFont systemFontOfSize:14] andWidth:Width-50];
            if (contentWidth > 60) {
                weakSelf.detailCarModel.isShowAllDetailDesc = @"1";
            }else {
                weakSelf.detailCarModel.isShowAllDetailDesc = @"0";
            }
            [weakSelf.tableView reloadData];
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:nil isSucceed:NO];
    }];
}


- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"分享标题" descr:@"我是被分享的内容" thumImage:@""];
    //设置网页地址
    shareObject.webpageUrl = @"http://www.baidu.com";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            [[BONoticeBar defaultBar] setNoticeText:@"取消分享"];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                [[BONoticeBar defaultBar] setNoticeText:@"分享成功"];
            }else{
                UMSocialLogInfo(@"response data is %@",data);
                [[BONoticeBar defaultBar] setNoticeText:@"分享失败"];
            }
            
        }
    }];
}

- (TDDriveCarDatePickerSelModel *)selDateModel {
    if (!_selDateModel) {
        _selDateModel = [[TDDriveCarDatePickerSelModel alloc] init];
    }
    return _selDateModel;
}

@end
